//
//  CZWebNoticeViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/22.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZWebNoticeViewController.h"
#import "CZEnrollViewController.h"
#import <WebKit/WebKit.h>
@interface CZWebNoticeViewController () <WKNavigationDelegate>

@end

@implementation CZWebNoticeViewController {
    BOOL _authenticated;
    NSURLConnection *_urlConnection;
    NSURLRequest *_request;
    UIWebView *_web;
    WKWebView *_wkWebView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.type;
    _authenticated = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    _wkWebView = [[WKWebView alloc] init];
    [self.view addSubview:_wkWebView];
    _wkWebView.navigationDelegate = self;
    [_wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
    }];
    
    if (_articleID) {
        [self getNewsData];
    } else {
        NSURL *URL = [NSURL URLWithString:_urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        _request = request;
        [_wkWebView loadRequest:request];
    }
//    if (_articleID) {
//        [self getNewsData];
//    } else {
//        UIWebView *webView = [[UIWebView alloc] init];
//        [self.view addSubview:webView];
//        _web = webView;
//        webView.delegate = self;
//        [webView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.bottom.equalTo(self.view);
//            make.top.equalTo(self.view).offset(64);
//        }];
//        NSURL *URL = [NSURL URLWithString:_urlString];
//        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//        _request = request;
//        [webView loadRequest:request];
//    }
    
    // Do any additional setup after loading the view.
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [SVProgressHUD show];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [SVProgressHUD dismiss];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [SVProgressHUD showErrorWithStatus:@"网络错误"];
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

- (void)getNewsData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/article/detail",APP_HOST];
    [GCZAFNetWorking POST:urlString params:@{@"article_id" : self.articleID} success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
//            UIWebView *webView = [[UIWebView alloc] init];
//            [self.view addSubview:webView];
//            webView.delegate = self;
//            _web = webView;
//            [webView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.left.right.equalTo(self.view);
//                make.top.equalTo(self.view).offset(64);
//                make.bottom.equalTo(self.view);
//            }];
            NSURL *URL = [NSURL URLWithString:response[@"result"][@"url"]];
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//            [webView loadRequest:request];
//            _request = request;
            [_wkWebView loadRequest:request];
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
    }];

}

//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
//{
//    NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);
//    
//    if (!_authenticated) {
//        
//        _authenticated = NO;
//        
//        _urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
//        
//        [_urlConnection start];
//        
//        return NO;
//    }
//    return YES;
//}
//
//#pragma mark - NURLConnection delegate
//
//- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
//{
//    NSLog(@"WebController Got auth challange via NSURLConnection");
//    
//    if ([challenge previousFailureCount] == 0)
//    {
//        _authenticated = YES;
//        
//        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//        
//        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
//        
//    } else
//    {
//        [[challenge sender] cancelAuthenticationChallenge:challenge];
//    }
//}
//
//// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.
//- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
//{
//    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
//}
//
//#pragma mark - NSURLConnectionDataDelegate
//
//- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
//{
//    NSLog(@"WebController received response via NSURLConnection");
//    
//    // remake a webview call now that authentication has passed ok.
//    _authenticated = YES;
//    [_web loadRequest:_request];
//    
//    // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
//    [_urlConnection cancel];
//}
//
//
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
//
//- (void)webViewDidStartLoad:(UIWebView *)webView {
//    [SVProgressHUD show];
//}
//
//- (void)webViewDidFinishLoad:(UIWebView *)webView {
//    [SVProgressHUD dismiss];
//}
//
//- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
//    [SVProgressHUD showErrorWithStatus:@"加载失败"];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc {
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
